<template>
  <div v-loading="loading" class="container">
    <el-card>
      <header class="header-container">
        <span class="left-container">
          <el-button type="primary" icon="el-icon-back" @click="back" />
          <span style="font-weight: bold; margin-left: 12px;">发货申请编号: {{ topData.applyNo }}</span>
        </span>
        <span>
          <el-button
            v-if="+topData.approveStatus===0 && isCurrentApproval(allData.currentApproveUserList, userAccount)"
            v-permission="['f01_02']"
            type="primary"
            @click="agree"
          >审批</el-button>
          <el-button
            v-if="+topData.approveStatus===0 && isCurrentApproval(allData.currentApproveUserList, userAccount)"
            v-permission="['f01_03']"
            type="primary"
            @click="reject"
          >驳回</el-button>
        </span>
      </header>
      <div style="margin-top: 16px;">
        <span v-if="topData.specialApprove===1" class="highlight-font">需要特批</span>
        <el-divider v-if="topData.specialApprove===1" direction="vertical" />
        <span v-if="topData.overdue" class="highlight-font decoration-line" @click="goToRemittance(topData)">有逾期</span>
        <el-divider v-if="topData.overdue" direction="vertical" />
        <span v-if="topData.overAmount>0" class="highlight-font">超出信用：{{ formatMoneyAmount(topData.overAmount) }}</span>
        <el-divider v-if="topData.overAmount>0" direction="vertical" />
        <span>{{ getStatusLabel(topData.approveStatus, 'approvalOptions') }}</span>
        <el-divider direction="vertical" />
        <span>{{ getStatusLabel(topData.deliverStatus, 'shipOptions') }}</span>
        <el-divider direction="vertical" />
        <span>{{ getStatusLabel(topData.paymentStatus, 'moneyBackOptions') }}</span>
      </div>
    </el-card>
    <el-card style="margin-top: 12px;">
      <el-tabs v-model="activeTab">
        <el-tab-pane label="基本信息" name="baseInfo">
          <BasicInfo :data.sync="allData" @reviewDetail="getDeliveryDetail" />
        </el-tab-pane>
        <el-tab-pane label="发货物流" name="delivery">
          <Delivery v-if="activeTab==='delivery'" :all-data.sync="allData" />
        </el-tab-pane>
        <el-tab-pane label="回款计划" name="repaymentplan">
          <RepaymentPlan :data.sync="allData" :money-back-options="moneyBackOptions" />
        </el-tab-pane>
        <el-tab-pane label="审批记录" name="detailAgreeInfo">
          <DetailAgreeInfo :approval-record-list="approvalRecordList" :loading="loadingApprovalRecord" />
        </el-tab-pane>
      </el-tabs>
    </el-card>
    <AgreeOrReject
      :title="title"
      :visible="visible"
      :submit-loading="submitLoading"
      :data="allData"
      :is-agree="isAgree"
      @close="visible = false"
      @submit="handleSubmit"
    />
  </div>
</template>

<script>
import BasicInfo from './components/BasicInfo'
import RepaymentPlan from './components/RepaymentPlan'
import AgreeOrReject from './components/AgreeOrReject'
import DetailAgreeInfo from './components/DetailAgreeInfo.vue'
import Delivery from './components/Delivery'
import { getDeliveryDetail, updateAgree, updateFail } from '@/service/ship'
import { approvalListRecord } from '@/service/approval'
import { Title } from './baseData'
import { mapActions } from 'vuex'
import { formatMoneyAmount, geneateAccountOrNameList } from '@/utils/tools'

export default {
  name: 'ShipDetail',
  components: {
    BasicInfo,
    RepaymentPlan,
    AgreeOrReject,
    Delivery,
    DetailAgreeInfo
  },
  data() {
    return {
      loading: false,
      loadingApprovalRecord: true,
      formatMoneyAmount,
      submitLoading: false,
      oaNumber: '', // OA申请编号
      id: '',
      activeTab: 'baseInfo',
      visible: false,
      title: Title.agree,
      approvalOptions: [], // 审批状态
      shipOptions: [], // 发货状态
      moneyBackOptions: [], // 回款状态
      topData: {
        specialApprove: 0,
        applyNo: '', // 发货申请编号
        overAmount: '', // 超出信用
        payFirstAmountStatus: true, // 已收到首款
        overdueStatus: false,
        approveStatus: '', // 审批状态
        deliverStatus: '', // 发货状态
        paymentStatus: '' // 回款状态
      },
      allData: {},
      approvalRecordList: [],
      isAgree: false
    }
  },
  computed: {
    userAccount() {
      return this.$store.state?.global?.user?.account || this.$store.state.user.account
    }
  },
  watch: {
    activeTab: {
      handler(val) {
        if (val === 'detailAgreeInfo') {
          this.handlerApprovalList()
        }
      }
    }
  },
  beforeMount() {
    const { params: { id }} = this.$route
    this.id = id
    this.initBaseData('approve_status', 'approvalOptions') // 审批状态
    this.initBaseData('deliver_status', 'shipOptions') // 发货状态
    this.initBaseData('payment_status', 'moneyBackOptions') // 回款状态
    this.getDictionary()
    this.getDeliveryDetail(id)
  },
  methods: {
    ...mapActions({ getBaseDataList: 'base/getBaseDataList' }),
    back() {
      this.$router.back()
    },
    initBaseData(type, optionName) {
      this.$store.dispatch('base/getBaseDataList', { type }).then(res => {
        this[optionName] = res
      })
    },
    getDictionary() {
      this.getBaseDataList({ type: 'country_code' })
      this.getBaseDataList({ type: 'currency' })
      this.getBaseDataList({ type: 'payment_stage' })
      this.getBaseDataList({ type: 'checking_status' })
      this.getBaseDataList({ type: 'trade_terms' })
      this.getBaseDataList({ type: 'forwarder_type' })
      this.getBaseDataList({ type: 'delivery_warehouse' })
      this.getBaseDataList({ type: 'transport_type' })
    },
    getDeliveryDetail(id) {
      this.loading = true
      getDeliveryDetail({ id }).then((data) => {
        this.allData = data
        this.activeTab = 'baseInfo'
        this.initTopData(data)
      }).finally(() => {
        this.loading = false
      })
    },
    initTopData(data) {
      const { applyNo, overAmount, payFirstAmountStatus, approveStatus, deliverStatus, paymentStatus, overdue, specialApprove } = data
      this.topData = {
        applyNo, overAmount, payFirstAmountStatus, approveStatus, deliverStatus, paymentStatus, overdue, specialApprove
      }
    },
    getStatusLabel(status, optionName) {
      const item = this[optionName].filter(item => `${item.value}` === `${status}`)[0]
      return item ? item.label : '-'
    },
    agree() {
      this.title = Title.agree
      this.isAgree = true
      this.visible = true
    },
    reject() {
      this.title = Title.reject
      this.isAgree = false
      this.visible = true
    },
    goToRemittance({ applyNo }) {
      if (window.__POWERED_BY_QIANKUN__) {
        window.open(`/fina-admin/remittance/remittanceList?applyNo=${applyNo}&isOverDue=true`)
      } else {
        window.open(`/remittance/remittanceList?applyNo=${applyNo}&isOverDue=true`)
      }
    },
    async handleSubmit(params) {
      this.submitLoading = true
      const fn = this.isAgree ? updateAgree : updateFail
      const message = this.isAgree ? '审批成功！' : '驳回成功！'
      await fn(params).finally(() => {
        this.submitLoading = false
      })
      this.$message({
        message,
        type: 'success'
      })
      await this.$store.dispatch('approvalAmount/getAwaitApprovalAmount', { waitApproveUserAccount: this.userAccount })
      this.handlerApprovalList()
      this.getDeliveryDetail(this.id)
      this.visible = false
    },
    async handlerApprovalList() {
      this.loadingApprovalRecord = true
      let currentIndex = 0
      /**
       * requestId 各种业务ID
       * requestNo 各种业务订单号
       * requestType PI、发货申请-delivery_apply、撤销核账-revoke_write_off
       */
      const param = {
        requestId: +this.id,
        requestNo: this.topData.applyNo,
        requestType: 'delivery_apply'
      }
      this.approvalRecordList = await approvalListRecord(param).finally(() => {
        this.loadingApprovalRecord = false
      }) || []
      /**
       * 因为要获取当前审批节点，而后端只返回两种节点类型，一种是history、一种是future，第一个future为当前审批节点,
       * 前端筛选出来了
       */
      for (let i = 0; i < this.approvalRecordList.length; i++) {
        if (this.approvalRecordList[i]?.recordType === 'future') {
          currentIndex = i
          break
        }
      }
      if (this.approvalRecordList[currentIndex]?.recordType === 'future') {
        this.approvalRecordList[currentIndex].recordType = 'current'
      }
    },
    isCurrentApproval(currentApproveUserList, userAccount) {
      const { accountList } = geneateAccountOrNameList(currentApproveUserList)
      return accountList.includes(userAccount)
    }
  }
}
</script>

<style lang="scss" scoped>
.container {
  margin: 12px;
  width: calc(100% - 24px);
  .header-container {
    display: flex;
    justify-content: space-between;
    .left-container {
      display: flex;
      align-items: center;
    }
  }
  .highlight-font {
    background-color: yellow;
  }
  .decoration-line {
    cursor: pointer;
    text-decoration: underline;
  }
}
</style>

<style lang="scss">
</style>
